package com.yixing.tech.entity.entity.attr;

import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.entity.entity.RequestType;
import com.yixing.tech.common.vo.s5.EntitySchema;
import org.springframework.data.mongodb.core.aggregation.*;

import java.util.List;

/**
 * @author yixing tech
 * at 2021/10/9
 * describe：
 */
public class TimeStatus extends AttrType {
    public TimeStatus() {
        super("时间状态", "timeStatus");
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr) throws BusinessException {
        super.out(operations, attr);
        String reference = attr.getReference().toString();
        String[] conf = reference.split(",");
        int limitSecond = Integer.parseInt(conf[2]);
        String[] format = attr.getValueFormat().split("/");
        ArithmeticOperators.Divide divide = ArithmeticOperators.Divide.valueOf(ArithmeticOperators.Subtract.valueOf("$$NOW").subtract(conf[0])).divideBy(1000);
        Object cond = format[0];
        switch (conf[1]) {
            case "gt":
                cond = ConditionalOperators.Cond.when(ComparisonOperators.Gt.valueOf(divide).greaterThanValue(limitSecond)).then(format[0]).otherwise(format[1]);
                break;
            case "gte":
                cond = ConditionalOperators.Cond.when(ComparisonOperators.Gte.valueOf(divide).greaterThanEqualToValue(limitSecond)).then(format[0]).otherwise(format[1]);
                break;
            case "lt":
                cond = ConditionalOperators.Cond.when(ComparisonOperators.Lt.valueOf(divide).lessThanValue(limitSecond)).then(format[0]).otherwise(format[1]);
                break;
            case "lte":
                cond = ConditionalOperators.Cond.when(ComparisonOperators.Lte.valueOf(divide).lessThanEqualToValue(limitSecond)).then(format[0]).otherwise(format[1]);
                break;
            default:
        }
        operations.add(Aggregation.addFields().addFieldWithValue(attr.getCode(), cond).build());
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr, RequestType requestType) throws BusinessException {
        out(operations, attr);
    }
}
